<template>
  <div id='electronic' class="set">
    <Row type="flex" align="middle" justify="center" class="set_ct">
      <Col>
        <Form ref="formDynamic" :model="formDynamic" :rules="ruleValidate" :label-width="180">
          <FormItem label="SVIP权益名称：" prop="pkgName">
            <Input v-model="formDynamic.pkgName"
              :maxlength="14"
              placeholder="最多可输入14字"
              style="width:280px" :disabled="isEdit"></Input>
            <span style="margin-left: 5px; color: #808695">SVIP权益名称保存后不支持修改</span>
          </FormItem>
          <FormItem label="SVIP价格：" prop="pkgPrice">
            <Input v-model="formDynamic.pkgPrice"
              placeholder="请输入"
              @on-keyup="filterPrice"
              @on-blur="filterPrice"
              style="width:280px"></Input>
            <span style="margin-left: 5px; color: #808695">元</span>
          </FormItem>
          <FormItem label="设置权益内容：" prop="rightsType">
            <CheckboxGroup v-model="formDynamic.rightsType" @on-change='changeRightsType'>
              <Checkbox label="1">优惠券</Checkbox>
              <Checkbox label="2" style="margin-left:30px">游戏券</Checkbox>
            </CheckboxGroup>
          </FormItem>
          <FormItem label="优惠券列表:" style="width: 830px" prop="items" v-if="formDynamic.rightsType.length > 0 &&formDynamic.rightsType.indexOf('1') !== -1">
            <select-setting-coupon v-model="formDynamic.items" @addcoupon="Dmodal = true" @couponchange="couponChange" :valid-period="formDynamic.validPeriod" @input="deleteCoupon"></select-setting-coupon>
          </FormItem>
          <!-- <FormItem label="总计发券数：" prop="total" v-if="formDynamic.items.length">
            <Input v-model="formDynamic.total"
              placeholder="自动计算"
              style="width:280px" disabled></Input>
              <span style="margin-left: 5px; color: #808695">张</span>
          </FormItem> -->
          <FormItem label="有效期：" prop="validPeriod" v-if="formDynamic.rightsType.length > 0 &&formDynamic.rightsType.indexOf('1') !== -1">
            <Input v-model="formDynamic.validPeriod"
              :maxlength="2"
              placeholder="请输入"
              @on-keyup="filterNumber('validPeriod')"
              @on-blur="blurNumber('validPeriod')"
              style="width:280px"></Input>
            <span style="margin-left: 5px; color: #808695">月</span>
          </FormItem>
          <FormItem label="游戏券列表：" prop="gameTicketList" v-if="formDynamic.rightsType.length > 0 &&formDynamic.rightsType.indexOf('2') !== -1">
            <div style=" position:relative;width:700px" id="drawTicket">
              <Table width="100%" :columns="ticketColumns" :data="formDynamic.gameTicketList">
                <template slot-scope="{ row }" slot="time">
                  <span>{{ row.listingTime }} - {{ row.delistingTime }}</span>
                </template>
              </Table>
              <div>
                <Icon type="ios-add-circle" size="24" color="#2D8CF0" class="coupon-addicon" @click='openDraw' />
              </div>
              <div v-if='formDynamic.gameTicketList &&formDynamic.gameTicketList.length > 0' @click="removeRow">
                <Icon type="md-trash" size="24"  color="#808695" class="coupon-removeicon" />
              </div>
            </div>
          </FormItem>
          <FormItem label="售价：" prop="salePrice">
            <Input v-model="formDynamic.salePrice"
              placeholder="自动计算"
              style="width:280px" disabled></Input>
              <span style="margin-left: 5px; color: #808695">元</span>
          </FormItem>
          <FormItem label="购买限制：" prop="pkgMemberLevel">
            <Select v-model="formDynamic.pkgMemberLevel"
              style="width:280px">
              <Option v-for="(item, index) in memberLevels" :value="item.memberLevel" :key="index">V{{ item.memberLevel }}</Option>
            </Select>
            <div style="display: inline-block; margin-left: 5px; color: #808695">
              <span>及以上</span>
              <Tooltip placement="right" style="margin-left: 5px; position: relative; top: 3px">
                <img src="@/assets/images/icon_description.svg" alt="">
                <div slot="content">
                  <p>默认选中最低等级，运营可根据配置调整购</p>
                  <p>买等级。如选择V1，代表V1及以上(含V1)</p>
                  <p>会员可购买。</p>
                </div>
              </Tooltip>
            </div>
          </FormItem>
          <FormItem label="大礼包说明：" prop="giftRemark">
            <Input v-model="formDynamic.giftRemark"
              placeholder="请输入"
              :maxlength="12"
              style="width:280px"></Input>
          </FormItem>
          <FormItem label="SVIP会员权益介绍：" prop="pkgDesc">
            <div ref="addEditor1" class="rich-editor"></div>
            <!-- <Input v-model="formDynamic.pkgDesc" placeholder="请描述会员权益" type="textarea" :autosize="{ minRows: 4, maxRows: 5 }" :maxlength="2000"></Input>
            <span class="rol_tipsd">
              {{ formDynamic.pkgDesc.length }}/2000
            </span> -->
          </FormItem>
          <FormItem label="SVIP会员卡使用说明：" prop="pkgRemark">
            <div ref="addEditor2" class="rich-editor"></div>
            <!-- <Input v-model="formDynamic.pkgRemark" placeholder="请描述会员卡使用说明" type="textarea" :autosize="{ minRows: 4, maxRows: 5 }" :maxlength="2000"></Input>
            <span class="rol_tipsd">
              {{ formDynamic.pkgRemark.length }}/2000
            </span> -->
          </FormItem>
          <FormItem label="SVIP售卖商品图:"
            prop="pkgImage"
            class="set_ct_form_up">
            <Upload ref="upload"
              :format="['jpg', 'png']"
              :max-size="100"
              :on-success="handleSuccess"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              type="drag"
              :show-upload-list="false"
              :action="$config.uploadImg"
              style="display: inline-block;width:96px;">
              <img :src="formDynamic.pkgImage ? formDynamic.pkgImage: defaultUrl"
                  style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                  alt="">
              <p v-if="formDynamic.pkgImage"
                class="replace_tit">更换</p>
            </Upload>
            <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;">
              <p>支持格式：.jpg、.png</p>
              <p>规格：220*170</p>
              <p>大小：≤100K</p>
            </div>
          </FormItem>
          <FormItem>
            <Button type="primary"  @click="handleSubmit" class="button">确定</Button>
            <!-- <Button @click="cancel" class="button btn1" >取消</Button> -->
            <Poptip transfer confirm title="取消编辑后输入的信息无法被保存，是否确定取消？" @on-ok="cancel" class="poptip_del">
              <Button class="button btn1">取消</Button>
            </Poptip>
          </FormItem>
        </Form>
      </Col>
    </Row>
    <drawer-coupon v-model="Dmodal" :data="formDynamic.items" :origin="3" @sure="handleSelectCoupon" expiration-type="0"></drawer-coupon>
    <drawer-gameticket v-model="drawStatus" :value='drawStatus' :ticketColumns='ticketColumns' :selectList='formDynamic.gameTicketList' @closeDraw='closeDraw' @selectedGame='selectedGame'></drawer-gameticket>
  </div>
</template>

<script>
import './index.less'
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import { createSalesPackage, getSvipCouponSetting, getSvipDetail } from '@/api/setting'
import { getMemberLevelList } from '@/api/member/index.js'
import DrawerCoupon from '@/view/components/drawer-coupon/index.vue'
import DrawerGameticket from '@/view/components/drawer-gameticket/index.vue'
import SelectSettingCoupon from '@/view/components/select-setting-coupon/index.vue'
import editor from '@/view/components/editor/mixins'
export default {
  mixins: [editor],
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.routerId !== to.query.id) {
        vm.shopId = to.query.id
        vm.paramter.shopId = to.query.id
        vm.getData()
      }
    })
  },
  components: { DrawerCoupon, SelectSettingCoupon, DrawerGameticket },
  watch: {
    'formDynamic.pkgPrice' (value) {
      if (this.formDynamic.rightsType.indexOf('2') !== -1) {
        this.formDynamic.salePrice = (Math.round(Number(this.formDynamic.pkgPrice) * 100 + Number(this.formDynamic.gameTicketList.length ? this.formDynamic.gameTicketList[0].price : 0) * 100) / 100).toFixed(2) + ''
      } else {
        this.formDynamic.salePrice = this.formDynamic.pkgPrice
      }
    }
  },
  data () {
    return {
      drawStatus: false,
      ticketColumns: [
        {
          title: '游戏券名称',
          key: 'name'
        },
        {
          title: '局数',
          key: 'round'
        },
        {
          title: '金额（元）',
          key: 'price'
        },
        {
          title: '有效时间',
          key: 'validPeriod'
        },
        {
          title: '上下架时间',
          slot: 'time',
          width: 160
        }
      ],
      isEdit: false,
      formDynamic: {
        pkgName: '',
        items: [],
        // total: '',
        giftRemark: '',
        validPeriod: '',
        pkgPrice: '',
        pkgMemberLevel: '',
        pkgDesc: '',
        pkgRemark: '',
        pkgImage: '',
        rightsType: [],
        gameTicketList: [],
        salePrice: ''
      },
      memberLevels: [],
      ruleValidate: {
        salePrice: { required: true, message: '售价不能为空', trigger: 'change' },
        gameTicketList: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.formDynamic.gameTicketList.length > 0) {
              callback()
            } else {
              callback(new Error('游戏券列表不能为空'))
            }
          }
        },
        rightsType: { required: true, type: 'array', message: '请选择设置权益内容', trigger: 'change' },
        pkgName: { required: true, message: '请输入SVIP权益名称', trigger: 'blur' },
        items: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.formDynamic.items.length) {
              callback()
            } else {
              callback(new Error('请选择优惠券'))
            }
          }
        },
        // total: { required: true, message: '自动计算发券总数量失败' },
        validPeriod: { required: true, message: '请输入有效期', trigger: 'blur' },
        pkgPrice: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!this.formDynamic.pkgPrice) {
              callback(new Error('请输入SVIP价格'))
            } else if (this.formDynamic.pkgPrice > 9999999999.99) {
              callback(new Error('SVIP价格不合理'))
            } else {
              callback()
            }
          }
        },
        giftRemark: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!this.formDynamic.giftRemark) {
              callback(new Error('请输入大礼包说明'))
            } else {
              callback()
            }
          }
        },
        pkgMemberLevel: { required: true, message: '请选择购买限制' },
        pkgDesc: { required: true, message: '请输入SVIP会员权益介绍', trigger: 'blur' },
        pkgRemark: { required: true, message: '请输入SVIP会员卡使用说明', trigger: 'blur' },
        pkgImage: { required: true, message: '请上传SVIP售卖商品图' }
      },
      Dmodal: false,
      defaultUrl: require('@/assets/images/add.png'),
      paramter: {
        'merchantId': this.$store.state.user.merchantId,
        'msType': '1',
        'shopId': this.$route.query.id
      },
      pkgId: ''
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userName: state => state.user.userName
    })
  },
  mounted () {
    this.shopId = this.$route.query.id
    this.getEnums()
    this.createEditor(this.$refs.addEditor1, () => {
      if (this.$editor.txt.html() === '<p><br></p>') {
        this.formDynamic.pkgDesc = ''
      } else {
        this.formDynamic.pkgDesc = this.$editor.txt.html()
      }
    })
    this.createEditor(this.$refs.addEditor2, () => {
      if (this.$editor2.txt.html() === '<p><br></p>') {
        this.formDynamic.pkgRemark = ''
      } else {
        this.formDynamic.pkgRemark = this.$editor2.txt.html()
      }
    }, 2)
  },
  methods: {
    changeRightsType () {
      if (this.formDynamic.rightsType.indexOf('2') !== -1) {
        this.formDynamic.salePrice = (Math.round(Number(this.formDynamic.pkgPrice) * 100 + Number(this.formDynamic.gameTicketList.length ? this.formDynamic.gameTicketList[0].price : 0) * 100) / 100).toFixed(2) + ''
      } else {
        this.formDynamic.salePrice = this.formDynamic.pkgPrice
      }
    },
    removeRow () {
      this.formDynamic.gameTicketList = []
      this.formDynamic.salePrice = this.formDynamic.pkgPrice
    },
    selectedGame (data) {
      this.formDynamic.gameTicketList = []
      this.formDynamic.gameTicketList = data
      this.$refs.formDynamic.validateField('gameTicketList')
      this.formDynamic.salePrice = (Math.round(Number(this.formDynamic.pkgPrice) * 100 + Number(this.formDynamic.gameTicketList[0].price) * 100) / 100).toFixed(2) + ''
    },
    closeDraw (data) {
      this.drawStatus = data
    },
    openDraw () {
      this.drawStatus = true
    },
    getData () {
      getSvipDetail({
        merchantId: this.merchantId,
        shopId: this.shopId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          if (result.data && result.data.pkgId) {
            this.pkgId = result.data.pkgId
            this.isEdit = true
            this.formDynamic = {
              pkgName: result.data.pkgName,
              items: [],
              // total: '',
              validPeriod: result.data.validPeriod + '',
              salePrice: result.data.pkgPrice + '',
              pkgPrice: '',
              giftRemark: result.data.giftRemark || '',
              pkgMemberLevel: result.data.pkgMemberLevel,
              pkgDesc: result.data.pkgDesc,
              pkgRemark: result.data.pkgRemark,
              pkgImage: result.data.pkgImage,
              rightsType: [],
              gameTicketList: []
            }
            this.$editorContent = result.data.pkgDesc || ''
            this.$editor.txt.html(result.data.pkgDesc || '')
            this.$editorContent2 = result.data.pkgRemark || ''
            this.$editor2.txt.html(result.data.pkgRemark || '')

            getSvipCouponSetting({
              merchantId: this.merchantId,
              shopId: this.shopId,
              pkgId: result.data.pkgId
            }).then(res => {
              if (res.data.status === 200) {
                // let total = 0
                if (res.data.data.couponList) {
                  if (res.data.data.couponList && res.data.data.gameCouponList) {
                    this.formDynamic.rightsType = ['1', '2']
                    this.formDynamic.gameTicketList = res.data.data.gameCouponList
                    this.formDynamic.pkgPrice = (Math.round(this.formDynamic.salePrice * 100 - res.data.data.gameCouponList[0].price * 100) / 100).toFixed(2) + ''
                  } else {
                    this.formDynamic.rightsType = ['1']
                    this.formDynamic.pkgPrice = this.formDynamic.salePrice
                  }
                  this.formDynamic.items = res.data.data.couponList.map(item => {
                    const accumAmount = (result.data.validPeriod / +item.period) * (+item.quantity)
                    // total += accumAmount
                    return {
                      accumAmount: accumAmount + '',
                      refId: item.couponId,
                      refName: item.couponName,
                      refType: item.couponType,
                      productPeriod: item.period,
                      productQty: item.quantity + ''
                    }
                  })
                } else {
                  this.formDynamic.gameTicketList = res.data.data.gameCouponList
                  this.formDynamic.rightsType = ['2']
                  this.formDynamic.pkgPrice = (Math.round(this.formDynamic.salePrice * 100 - res.data.data.gameCouponList[0].price * 100) / 100).toFixed(2) + ''
                }
                // this.formDynamic.total = total
              } else {
                this.$Message.error(`${result.error}`)
              }
            })
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    handleSubmit () {
      if (this.$editor.txt.html() === '<p><br></p>') {
        this.$Message.error('请输入SVIP会员权益介绍')
        return
      }
      if (this.$editor.txt.html().length > 2000) {
        this.$Message.error('SVIP会员权益介绍不能超过2000个字符')
        return
      }
      if (this.$editor2.txt.html() === '<p><br></p>') {
        this.$Message.error('请输入SVIP会员卡使用说明')
        return
      }
      if (this.$editor2.txt.html().length > 2000) {
        this.$Message.error('SVIP会员卡使用说明不能超过2000个字符')
        return
      }
      this.$refs.formDynamic.validate((valid) => {
        if (valid) {
          const data = {
            pkgName: this.formDynamic.pkgName,
            validPeriod: this.formDynamic.validPeriod,
            pkgPrice: this.formDynamic.salePrice,
            giftRemark: this.formDynamic.giftRemark,
            pkgMemberLevel: this.formDynamic.pkgMemberLevel,
            pkgType: '5',
            pkgRemark: this.$editor2.txt.html(),
            pkgDesc: this.$editor.txt.html(),
            status: '1',
            pkgImage: this.formDynamic.pkgImage,
            creator: this.userName,
            items: []
          }
          if (this.formDynamic.rightsType.indexOf('1') !== -1) {
            data.items = this.formDynamic.items.map(item => {
              return {
                productName: item.refName,
                productQty: item.productQty,
                productPeriod: item.productPeriod,
                refId: item.refId,
                productSku: 'COUPON0001'
              }
            })
            if (this.formDynamic.rightsType.indexOf('2') !== -1) {
              data.items.push({
                productName: this.formDynamic.gameTicketList[0].name,
                productSku: this.formDynamic.gameTicketList[0].gameCouponCode
              })
            }
          } else {
            data.items.push({
              productName: this.formDynamic.gameTicketList[0].name,
              productSku: this.formDynamic.gameTicketList[0].gameCouponCode
            })
          }
          if (this.pkgId) {
            data.pkgId = this.pkgId
          }
          let obj = Object.assign({}, this.paramter, data)
          createSalesPackage(obj).then((res) => {
            if (res.data.status === 200) {
              this.$Message.success('设置成功!')
              this.closeModal()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    handleSelectCoupon (val) {
      const defaultVal = 1
      let accumAmount = ''
      if (this.formDynamic.validPeriod) {
        accumAmount = (+this.formDynamic.validPeriod / defaultVal) * defaultVal
      }
      this.formDynamic.items = val.map(item => {
        return {
          ...item,
          accumAmount,
          productPeriod: defaultVal,
          productQty: '' + defaultVal
        }
      })
      this.calcTotal()
      this.$refs.formDynamic.validateField('items')
    },
    getEnums () {
      getMemberLevelList({
        merchantId: this.merchantId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.memberLevels = result.data || []
          this.formDynamic.pkgMemberLevel = this.memberLevels[0] ? this.memberLevels[0].memberLevel : ''
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    filterNumber (prop) {
      this.formDynamic[prop] = this.formDynamic[prop].replace(/[\D\s]/g, '')
      if (this.formDynamic[prop][0] === '0') {
        this.formDynamic[prop] = this.formDynamic[prop].substr(1, 1)
      }
    },
    blurNumber (prop) {
      this.filterNumber(prop)
      if (this.formDynamic[prop]) {
        this.formDynamic.items = this.formDynamic.items.map(item => {
          item.accumAmount = (+this.formDynamic[prop] / +item.productPeriod) * (+item.productQty) + ''
          return item
        })
      }
      this.calcTotal()
    },
    deleteCoupon () {
      this.calcTotal()
    },
    couponChange (val, index) {
      this.formDynamic.items[index] = val
      this.calcTotal()
    },
    calcTotal () {
      this.formDynamic.total = this.formDynamic.items.map(item => item.accumAmount).reduce((total, num) => +num + (+total))
    },
    filterPrice () {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (this.formDynamic.pkgPrice !== '' && this.formDynamic.pkgPrice.substring(0, 1) === '.') {
        this.formDynamic.pkgPrice = ''
      }
      this.formDynamic.pkgPrice = this.formDynamic.pkgPrice.replace(/\s+/g, '')
      this.formDynamic.pkgPrice = this.formDynamic.pkgPrice.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      this.formDynamic.pkgPrice = this.formDynamic.pkgPrice.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      this.formDynamic.pkgPrice = this.formDynamic.pkgPrice.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formDynamic.pkgPrice = this.formDynamic.pkgPrice.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      if (this.formDynamic.pkgPrice.indexOf('.') < 0 && this.formDynamic.pkgPrice !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        this.formDynamic.pkgPrice = parseFloat(this.formDynamic.pkgPrice) + ''
      }
    },
    handleSuccess (response, file, fileList) {
      this.getcicun(response.full_img_url)
    },
    getcicun (url) {
      var img = new Image()
      img.src = url
      var _this = this
      img.onload = function () {
        if (img.width !== 220 || img.height !== 170) {
          _this.formDynamic.pkgImage = ''
          _this.$Notice.warning({
            title: '上传的图片规格不符'
          })
        } else {
          _this.formDynamic.pkgImage = url
          _this.$refs.formDynamic.validateField('pkgImage')
        }
      }
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '上传的图片大小不能超过100k'
      })
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传的图片格式错误'
      })
    },
    cancel () {
      this.closeModal()
    },
    closeModal () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      if (this.$store.state.app.tagNavList[this.$store.state.app.tagNavList.length - 1].name !== 'store_setting') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'store_setting', params: { id: this.shopId }
          })
        })
      }
    }
  }
}
</script>

<style lang="less">
.set_ct_form_up .ivu-form-item-content {
  display: flex
}
.ivu-upload {
  width: 96px;
  height: 96px;
  position: relative;
  .replace_tit {
    position: absolute;
    bottom: 0;
    width: 96px;
    opacity: 0.6;
    background: #2d8cf0;
    height: 24px;
    text-align: center;
    line-height: 24px;
    font-size: 12px;
    color: #ffffff;
    display: none;
  }
}
.rol_tipsd {
  position: absolute;
  right: 0;
  bottom: -20px
}
</style>
<style lang='less' scoped>
  .coupon-addicon{ position:absolute;  right:-70px; top:50px; cursor: pointer; }
  .coupon-removeicon{ position:absolute; right:-40px; top:50px; cursor: pointer;}
</style>
